package com.xiaoluo.a15_loopviewgroup;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Base64;
import android.util.Log;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2015/12/8.
 */
public class LoopGroupView extends FrameLayout {
    private static final String TAG = "LoopGroupView";

    /**
     * 动画间隔
     */
    private static final int ANIM_DELAYED_MILLIONS = 3 * 1000;
    /**
     * 动画持续时长
     */
    private static final int ANIM_DURATION = 1 * 1000;
    private Animation anim_out, anim_in;
    private FrameLayout tv_tip_out, tv_tip_in;
    /**
     * 循环播放的消息
     */
    private List<SearchAppName.DataBean.CasesBean> tipList;
    /**
     * 当前轮播到的消息索引
     */
    private int curTipIndex = 0;
    private long lastTimeMillis;
    private LinearLayout mBottomLayout;
    private LinearLayout mTopLayout;

    public LoopGroupView(Context context) {
        this(context, null);
    }

    public LoopGroupView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoopGroupView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initTipFrame();
        setBackgroundColor(Color.parseColor("#00FFFF"));
        initAnimation();
    }

    private void initTipFrame() {

        tv_tip_out = newFrameLayout();
        tv_tip_in = newFrameLayout();
        addView(tv_tip_in);
        addView(tv_tip_out);
    }


    public void setTipList(List<SearchAppName.DataBean.CasesBean> casesBeanList) {
        this.tipList = casesBeanList;
        curTipIndex = 0;
        updateTip(tv_tip_out);
        invalidate();
        updateTipAndPlayAnimation();
    }

    private void initAnimation() {
        anim_out = newAnimation(0, -1);//向上位移  动画1秒 ，间隔3秒
        anim_in = newAnimation(1, 0);//从下面出来
        anim_in.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                updateTipAndPlayAnimationWithCheck();//动画结束之后
            }
        });
    }

    private void updateTipAndPlayAnimation() {//动画结束之后，更新内容 两个TextView 轮流切换
        if (curTipIndex % 2 == 0) {
            updateTip(tv_tip_out);//更新内容
            tv_tip_in.startAnimation(anim_out);
            tv_tip_out.startAnimation(anim_in);
            this.bringChildToFront(tv_tip_in);
        } else {
            updateTip(tv_tip_in);
            tv_tip_out.startAnimation(anim_out);
            tv_tip_in.startAnimation(anim_in);
            this.bringChildToFront(tv_tip_out);
        }
    }

    private void updateTipAndPlayAnimationWithCheck() {
        if (System.currentTimeMillis() - lastTimeMillis < 1000) {
            return;
        }
        lastTimeMillis = System.currentTimeMillis();
        updateTipAndPlayAnimation();
    }

    List<TextView> mTextViewList = new ArrayList<>();
    List<Integer> mWidthList = new ArrayList<>();
    int allLength = 0;

    private void updateTip(FrameLayout layout) {//更新内容
        mTextViewList.clear();
        allLength = 0;
        mWidthList.clear();
        layout.removeAllViews();
        final SearchAppName.DataBean.CasesBean casesBean = getNextTip();
        final int size = casesBean.appCnName.size();
        for (int i = 0; i < size; i++) {
            TextView textView = new TextView(getContext());
            textView.setTextSize(UiUtil.dpi(36));
            textView.setTextColor(Color.parseColor("#000000"));
            textView.setIncludeFontPadding(false);
            textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            textView.setText(casesBean.appCnName.get(i).sectionChinese);
            int width = (int) textView.getPaint().measureText(textView.getText().toString());
            mWidthList.add(width);
            mTextViewList.add(textView);
            allLength = width + allLength + UiUtil.div(30);
        }
        allLength = allLength - UiUtil.div(30);
        int initMargin = (UiUtil.div(400) - allLength) / 2;
        final LinearLayout mBottomLayout = new LinearLayout(getContext());
        mBottomLayout.setOrientation(LinearLayout.HORIZONTAL);
        FrameLayout.LayoutParams bottomParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        bottomParams.topMargin = UiUtil.div(58);
        if (layout.getChildCount() == 0) {
            layout.addView(mBottomLayout, bottomParams);
        }

        for (int i = 0; i < mTextViewList.size(); i++) {
            TextView textView = mTextViewList.get(i);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams();
            if (i == 0) {
                params.leftMargin = initMargin;
            } else {
                params.leftMargin = UiUtil.div(30);
            }
            mBottomLayout.addView(textView, params);
        }
        final FrameLayout mTopLayout = new FrameLayout(getContext());
        FrameLayout.LayoutParams topParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        topParams.topMargin = UiUtil.div(20);
        if (layout.getChildCount() == 1) {
            layout.addView(mTopLayout, topParams);
        }

        for (int i = 0; i < size; i++) {
            TextView textView = new TextView(getContext());
            textView.setTextSize(UiUtil.dpi(28));
            textView.setTextColor(Color.parseColor("#000000"));
            textView.setIncludeFontPadding(false);
            SearchAppName.DataBean.CasesBean.AppCnNameBean bean = casesBean.appCnName.get(i);
            if (bean.isHighLight) {
                SpannableStringBuilder stringBuilder = new SpannableStringBuilder(bean.sectionEnglish);
                stringBuilder.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                textView.setText(stringBuilder);
            } else {
                textView.setText(casesBean.appCnName.get(i).sectionEnglish);
            }
            int topTextMargin = initMargin;
            for (int j = 0; j - 1 < i; j++) {
                if (j == 0) {
                    topTextMargin = initMargin;
                } else {
                    topTextMargin = topTextMargin + mWidthList.get(j - 1) + UiUtil.div(30);
                }
            }
            topTextMargin = (int) (topTextMargin + mWidthList.get(i) / 2 - textView.getPaint().measureText(casesBean.appCnName.get(i).sectionEnglish) / 2);
            Log.i(TAG, "updateTip: " + topTextMargin);
            LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            textParams.leftMargin = topTextMargin;
            mTopLayout.addView(textView, textParams);
        }
    }


    /**
     * 获取下一条消息
     *
     * @return
     */
    private SearchAppName.DataBean.CasesBean getNextTip() {
        if (isListEmpty(tipList)) {
            return null;
        }
        return tipList.get(curTipIndex++ % tipList.size());
    }

    private FrameLayout newFrameLayout() {
        FrameLayout layout = new FrameLayout(getContext());
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(UiUtil.div(400), UiUtil.div(114));
        layout.setLayoutParams(layoutParams);
        return layout;
    }

    private Animation newAnimation(float fromYValue, float toYValue) {
        Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, fromYValue, Animation.RELATIVE_TO_SELF, toYValue);//上下位移动画，
        anim.setDuration(ANIM_DURATION);//动画时长
        anim.setStartOffset(ANIM_DELAYED_MILLIONS);//动画间隔
        anim.setInterpolator(new DecelerateInterpolator());
        return anim;
    }


    /**
     * list是否为空
     *
     * @param list
     * @return true 如果是空
     */
    public static boolean isListEmpty(List list) {
        return list == null || list.isEmpty();
    }


}
